package es.hekorusoft.udpcache.messages;

import java.io.ByteArrayInputStream;
import java.io.ObjectInputStream;
import java.nio.ByteBuffer;
import java.util.zip.GZIPInputStream;

/*
 This file is part of UDPCache.

 UDPCache is free software: you can redistribute it and/or modify
 it under the terms of the GNU General Public License as published by
 the Free Software Foundation, either version 3 of the License, or
 (at your option) any later version.

 UDPCache is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU General Public License for more details.

 You should have received a copy of the GNU General Public License
 along with UDPCache.  If not, see <http://www.gnu.org/licenses/>.
 */
final class ByteBufferReader {

	private ByteBuffer buf;

	public ByteBufferReader(ByteBuffer data) {
		this.buf = data;
		this.buf.rewind();
	}

	public final int getByte() {
		return buf.get();
	}

	public final int getInt() {
		return buf.getInt();
	}

	public final long getLong() {
		return buf.getLong();
	}

	public final String getString() {
		int size = buf.getInt();
		byte[] dest = new byte[size];
		buf.get(dest);
		return new String(dest);
	}

	public final Object getObject() {
		int size = buf.getInt();
		byte[] dest = new byte[size];
		buf.get(dest);
		Object obj = null;
		ByteArrayInputStream bais = new ByteArrayInputStream(dest);
		ObjectInputStream ois;
		try {
			if (dest[0] == 31 && dest[1] == -117 && dest[2] == 8) {
				ois = new ObjectInputStream(new GZIPInputStream(bais));
			} else {
				ois = new ObjectInputStream(bais);
			}
			obj = ois.readObject();
			ois.close();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return obj;

	}

	public final byte[] getByteArray() {
		int size = getInt();
		byte[] obj = new byte[size];
		buf.get(obj);
		return obj;
	}
}
